<template>
  <div class="app-container">
    <!-- 搜索栏 -->
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="名称" prop="name">
        <el-input v-model="queryParams.name" clearable placeholder="请输入名称" style="width: 240px" @change="handQuery" />
      </el-form-item>
      <el-form-item label="等级" prop="level">
        <el-select
          v-model="queryParams.level"
          multiple
          clearable
          collapse-tags
          collapse-tags-tooltip
          placeholder="请选择等级"
          @change="handQuery"
          style="width: 240px"
          :max-collapse-tags="2"
          popper-class="hospital-level-select"
        >
          <el-option v-for="item in levelOptions" :key="item.value" :value="item.value" :label="item.label" />
        </el-select>
      </el-form-item>
      <el-form-item label="类型" prop="type">
        <el-select v-model="queryParams.type" clearable placeholder="请选择类型" style="width: 240px" @change="handQuery">
          <el-option label="综合医院" value="综合医院"></el-option>
          <el-option label="专科医院" value="专科医院"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="创建时间" prop="dateRange" style="width: 308px">
        <el-date-picker
          v-model="dateRange"
          type="daterange"
          value-format="YYYY-MM-DD"
          range-separator="-"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          @change="handQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <!-- 操作按钮 -->
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="Plus" @click="handleAdd">新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="success" plain icon="Edit" :disabled="single" @click="handleUpdate">修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="danger" plain icon="Delete" :disabled="multiple" @click="handleDelete">删除</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList" :columns="columns"></right-toolbar>
    </el-row>

    <!-- 数据表格 -->
    <el-table v-loading="loading" :data="hospitalList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" align="center" width="50" />
      <el-table-column align="center" label="序号" width="50" v-if="columns.id.visible">
        <template #default="scope">
          {{ (queryParams.pageNum - 1) * queryParams.pageSize + scope.$index + 1 }}
        </template>
      </el-table-column>
      <el-table-column prop="name" align="center" label="名称" :show-overflow-tooltip="true" v-if="columns.name.visible"></el-table-column>
      <el-table-column prop="avatar" align="center" label="图片" v-if="columns.avatar.visible">
        <template #default="scope">
          <el-image
            v-if="scope.row.avatar"
            style="height: 60px"
            :src="scope.row.avatar"
            fit="cover"
            :preview-src-list="[scope.row.avatar]"
            :preview-teleported="true"
          />
          <span v-else>暂无图片</span>
        </template>
      </el-table-column>
      <el-table-column prop="level" align="center" label="等级" v-if="columns.level.visible"></el-table-column>
      <el-table-column prop="type" align="center" label="类型" v-if="columns.type.visible">
        <template #default="scope">
          <el-tag :type="scope.row.type === '综合医院' ? 'success' : 'primary'">
            {{ scope.row.type }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="introduction" align="center" label="简介" :show-overflow-tooltip="true" v-if="columns.introduction.visible"></el-table-column>
      <el-table-column prop="address" align="center" label="地址" :show-overflow-tooltip="true" v-if="columns.address.visible"></el-table-column>
      <el-table-column prop="createTime" align="center" label="创建时间" v-if="columns.createTime.visible"> </el-table-column>
      <el-table-column align="center" label="操作" class-name="small-padding fixed-width" v-if="columns.action.visible">
        <template #default="scope">
          <el-tooltip content="查看医院项目" placement="top">
            <el-button link type="primary" icon="View" @click="handleViewItems(scope.row)"></el-button>
          </el-tooltip>
          <el-tooltip content="编辑" placement="top">
            <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)"></el-button>
          </el-tooltip>
          <el-tooltip content="删除" placement="top">
            <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)"></el-button>
          </el-tooltip>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <pagination v-show="total > 0" :total="total" v-model:page="queryParams.pageNum" v-model:limit="queryParams.pageSize" @pagination="getList" />

    <el-dialog v-model="open" :title="title" width="600px" append-to-body>
      <!-- 添加或修改医院对话框 -->
      <el-form :model="form" ref="hospitalRef" :rules="rules" label-width="80px">
        <el-form-item label="名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入名称" />
        </el-form-item>
        <el-form-item label="图片" prop="avatar">
          <image-upload v-model="form.avatar" :limit="1" />
        </el-form-item>
        <el-form-item label="等级" prop="level">
          <el-select v-model="form.level" placeholder="请选择等级" popper-class="hospital-level-select">
            <el-option v-for="item in levelOptions" :key="item.value" :value="item.value" :label="item.label" />
          </el-select>
        </el-form-item>
        <el-form-item label="类型" prop="type">
          <el-select v-model="form.type" placeholder="请选择类型" style="width: 100%">
            <el-option v-for="item in typeOptions" :key="item.value" :value="item.value" :label="item.label" />
          </el-select>
        </el-form-item>
        <el-form-item label="简介" prop="introduction">
          <el-input v-model="form.introduction" :rows="4" type="textarea" :maxlength="300" show-word-limit resize="none" placeholder="请输入简介" />
        </el-form-item>
        <el-form-item label="地址" prop="address">
          <el-input v-model="form.address" placeholder="请输入地址">
            <template #append>
              <el-button icon="Location" @click="openMapSelector" />
            </template>
          </el-input>
        </el-form-item>
        <el-form-item label="经度" prop="longitude">
          <el-input v-model="form.longitude" placeholder="请输入经度" />
        </el-form-item>
        <el-form-item label="纬度" prop="latitude">
          <el-input v-model="form.latitude" placeholder="请输入纬度" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
    <!-- 医院项目信息对话框 -->
    <HospitalItemsInfo 
      :hospitalItemsInfoVisible="hospitalItemsInfoVisible" 
      :hospitalItemsList="currentHospitalItems" 
      @handleCancel="hospitalItemsInfoClose"
    />
    <!-- 地图选择器 -->
    <MapContainer ref="mapSelectorRef" @selected="handleLocationSelected" />
  </div>
</template>

<script setup name="Hospital">
import { listHospital, getHospital, delHospital, addHospital, updateHospital, getHospitalItems } from "@/api/hospital/hospital";
import MapContainer from "./components/MapContainer.vue";
import HospitalItemsInfo from "./components/HospitalItemsInfo.vue";

const { proxy } = getCurrentInstance();
const mapSelectorRef = ref(null);

// 响应式数据
const showSearch = ref(true);
const dateRange = ref([]);
const hospitalList = ref([]);
const loading = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const open = ref(false);
const title = ref("");
const hospitalItemsInfoVisible = ref(false);
const currentHospitalItems = ref([]);

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    name: undefined,
    level: [], // 改为数组支持多选
    type: undefined,
    startTime: undefined,
    endTime: undefined,
  },
  rules: {
    name: [{ required: true, message: "名称不能为空", trigger: "blur" }],
    avatar: [{ required: true, message: "图片不能为空", trigger: "blur" }],
    level: [{ required: true, message: "等级不能为空", trigger: "change" }],
    type: [{ required: true, message: "类型不能为空", trigger: "change" }],
    introduction: [{ required: true, message: "简介不能为空", trigger: "blur" }],
    address: [{ required: true, message: "地址不能为空", trigger: "blur" }],
    longitude: [{ required: true, message: "经度不能为空", trigger: "blur" }],
    latitude: [{ required: true, message: "纬度不能为空", trigger: "blur" }],
  },
});


// 列显隐信息
const columns = ref({
  id: { label: "序号", visible: true },
  name: { label: "名称", visible: true },
  avatar: { label: "头像", visible: true },
  level: { label: "登记", visible: true },
  type: { label: "类型", visible: true },
  introduction: { label: "简介", visible: true },
  address: { label: "地址", visible: true },
  createTime: { label: "创建时间", visible: true },
  action: { label: "操作", visible: true },
});

// 等级选项
const levelOptions = [
  { label: "三甲", value: "三甲" },
  { label: "三乙", value: "三乙" },
  { label: "三丙", value: "三丙" },
  { label: "二甲", value: "二甲" },
  { label: "二乙", value: "二乙" },
  { label: "二丙", value: "二丙" },
  { label: "一甲", value: "一甲" },
  { label: "一乙", value: "一乙" },
  { label: "一丙", value: "一丙" },
];

// 类型选项
const typeOptions = [
  { label: "综合医院", value: "综合医院" },
  { label: "专科医院", value: "专科医院" },
];

const { form, rules, queryParams } = toRefs(data);


const handleSelectionChange = (selection) => {
  ids.value = selection.map((item) => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
};

// 打开地图选择器
const openMapSelector = () => {
  if (mapSelectorRef.value) {
    mapSelectorRef.value.openDialog();
  }
};

// 地图选择回填
const handleLocationSelected = (payload) => {
  if (!payload) return;
  form.value.address = payload.address;
  if (payload.location) {
    form.value.longitude = payload.location.lng;
    form.value.latitude = payload.location.lat;
  }
};

const getList = () => {
  loading.value = true;

  // 处理日期范围查询
  if (dateRange.value && dateRange.value.length === 2) {
    queryParams.value.startTime = dateRange.value[0] + " 00:00:00";
    queryParams.value.endTime = dateRange.value[1] + " 00:00:00";
  } else {
    queryParams.value.startTime = undefined;
    queryParams.value.endTime = undefined;
  }
  listHospital(queryParams.value).then((res) => {
    loading.value = false;
    hospitalList.value = res.rows;
    total.value = res.total;
  });
};

const handQuery = () => {
  queryParams.value.pageNum = 1;
  getList();
};

const resetQuery = () => {
  dateRange.value = [];
  queryParams.value.startTime = undefined;
  queryParams.value.endTime = undefined;
  proxy.resetForm("queryRef");
  handQuery();
};

const handleAdd = () => {
  reset();
  open.value = true;
  title.value = "新增医院";
};

const handleUpdate = (row) => {
  reset();
  const id = row.id || ids.value;
  getHospital(id).then((res) => {
    form.value = res.data;
    open.value = true;
    title.value = "修改医院";
  });
};

const handleDelete = (row) => {
  let confirmText = "";
  let hospitalIds = null;
  if (row.id) {
    const index = hospitalList.value.findIndex((item) => item.id === row.id);
    confirmText += index + 1 + "、";
    hospitalIds = row.id;
  } else {
    ids.value.forEach((id) => {
      const index = hospitalList.value.findIndex((item) => item.id === id);
      confirmText += index + 1 + "、";
    });
    hospitalIds = ids.value;
  }
  proxy.$modal
    .confirm('是否确认删除医院序号为"' + confirmText.slice(0, -1) + '"的数据项？')
    .then(function () {
      return delHospital(hospitalIds);
    })
    .then(() => {
      getList();
      proxy.$modal.msgSuccess("删除成功");
    })
    .catch(() => {});
};

const submitForm = () => {
  proxy.$refs["hospitalRef"].validate((valid) => {
    if (valid) {
      if (form.value.id !== undefined) {
        updateHospital(form.value).then((res) => {
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          getList();
        });
      } else {
        addHospital(form.value).then((res) => {
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          getList();
        });
      }
    }
  });
};

const cancel = () => {
  open.value = false;
  reset();
};

const reset = () => {
  form.value = {
    id: undefined,
    name: undefined,
    avatar: undefined,
    level: levelOptions[0].value,
    type: typeOptions[0].value,
    introduction: undefined,
    address: undefined,
    longitude: undefined,
    latitude: undefined,
  };
  proxy.resetForm("hospitalRef");
};

const handleViewItems = (row) => {
  // 获取医院的项目信息
  getHospitalItems(row.id).then((res) => {
    currentHospitalItems.value = res.data || [];
    hospitalItemsInfoVisible.value = true;
  })
};

const hospitalItemsInfoClose = () => {
  hospitalItemsInfoVisible.value = false;
};

getList();
</script>
